<?php

    class CPageGzip
    {
	
	 static function &GetInstance()
	 {
	    global $g_hObjects;
	    static $m_hApp = NULL;
					 
	    if(!isset($m_hApp))
	    {
		$m_hApp = new CPageGzip();					 
		$g_hObjects[] = $m_hApp;
		$m_hApp->OnInit();
	    }
		
	    return $m_hApp;
	}
	
	function OnInit()
	{
	    
	    if(!extension_loaded('zlib'))
	    {
			$this->OnNoZLib();
			return;
	    }
	    
	    ob_implicit_flush(0);
	    
	    ini_set('zlib.output_compression_level', intval(GZIP_LEVEL));
	}
	
	function OnDestroy()
	{
	}

	/* processing if no zlib has benn found */
	function OnNoZLib()
	{
		throw new Exception('class CPageGzip::OnNoZLib() - brak biblioteki zlib');
	}
	
	/* start page buffering */
	function Start()
	{
	    //ob_clean();
	    ob_start();
	}
	
	/* send buffer content to browser */
	function SendToBrowser()
	{
	    $szContent = ob_get_contents();
	    $iContentLen =  ob_get_length();
	    
	    ob_end_clean();
			
	    //if headers were sent...
	    if(headers_sent($szFile,$szLine))
	    {	
			throw new Exception('class CPageGzip::SendToBrowser() - nagłówek HTTP został wysłany - plik: '.$szFile.' linia: '.$szLine);
	    }
	    
	    //$szEncoding = GetUserAgentEncoding();
		$szEncoding =  CRequest::GetAcceptedEncoding();

	    if(strstr($szEncoding,'gzip'))
	    {
	    	//andrew
			header('Content-Encoding: gzip');
			header('Vary: Accept-Encoding');
			header('Content-encoding: gzip');
            
			echo gzencode($szContent,intval(GZIP_LEVEL));
            	
			//echo $szContent;
	    }
	    else
	    {
			//no gzip encoding supported by the browser
			//echo $szContent;
			/*andrew*/
			echo $szContent;
	    }
	}
    }

?>